package com.by.service.impl;

import com.by.api.product.SpuRemoteClient;
import com.by.api.product.bean.StockBean;
import com.by.common.core.exception.BusinessException;
import com.by.common.core.utils.Assert;
import com.by.entity.Order;
import com.by.entity.OrderAddr;
import com.by.common.dao.MyBaseServiceImpl;
import com.by.mapper.OrderAddrMapper;
import com.by.mapper.OrderItemMapper;
import com.by.mapper.OrderMapper;
import com.by.service.OrderService;
import com.by.common.bean.ResultBean;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class OrderServiceImpl extends MyBaseServiceImpl<Order, OrderMapper> implements OrderService {

    @Autowired
    OrderAddrMapper orderAddrMapper;

    @Autowired
    OrderItemMapper orderItemMapper;

    @Autowired
    SpuRemoteClient spuRemoteClient;


    @GlobalTransactional
    @Override
    public int saveEntity(Order entity) {
        //保存收货地址
        OrderAddr addr = entity.getOrderAddr();
        int rs = orderAddrMapper.insert(addr);
        Assert.IS_FAILL(rs, "保存收货地址失败");
        //设置收货地址id
        entity.setOrder_addr_id(addr.getOrder_addr_id());
        //保存订单
        rs = super.saveEntity(entity);
        Assert.IS_FAILL(rs, "保存订单失败");
        //保存明细
        if (null != entity.getOrderItemList() && entity.getOrderItemList().size() > 0) {
            rs = orderItemMapper.batchSave(entity.getOrder_id(), entity.getOrderItemList());
            Assert.IS_FAILL(rs, "保存订单明细失败");

            //更新库存
            List<StockBean> beanList = new ArrayList<>();
            //遍历明细
            entity.getOrderItemList().forEach(el -> {
                beanList.add(new StockBean(el.getSpu_id(), el.getSku_id(), el.getCount(), entity.getOrder_id()));
            });
            //更新库存
            ResultBean resultBean = spuRemoteClient.updateStock(beanList);
            if (resultBean.getCode() != 200) {
                throw new BusinessException("更新库存失败:" + resultBean.getMsg());
            }
        }

        return 1;
    }
}
